package com.zzw.springboot.security;

import com.zzw.springboot.bean.SysPermission;
import com.zzw.springboot.bean.SysRole;
import com.zzw.springboot.bean.SysUser;
import com.zzw.springboot.mapper.SysPermissionMapper;
import com.zzw.springboot.mapper.SysRoleMapper;
import com.zzw.springboot.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Spring Security用户详情服务实现
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private SysRoleMapper roleMapper;
    
    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询用户
        SysUser user = userMapper.selectUserByUsername(username);
        
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在: " + username);
        }
        
        // 获取用户权限列表
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        
        // 查询用户角色
        List<SysRole> roles = roleMapper.selectRolesByUserId(user.getId());
        for (SysRole role : roles) {
            // 添加角色，需要添加前缀"ROLE_"
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));
            
            // 查询角色对应的权限
            List<SysPermission> permissions = permissionMapper.selectPermissionsByRoleId(role.getId());
            // 添加权限
            authorities.addAll(permissions.stream()
                    .map(permission -> new SimpleGrantedAuthority(permission.getPermissionCode()))
                    .collect(Collectors.toList()));
        }
        
        // 返回UserDetails实现
        return new User(
                user.getUsername(),
                user.getPassword(),
                user.getStatus() == 1, // 账号是否启用
                true, // 账号是否过期
                true, // 密码是否过期
                true, // 账号是否锁定
                authorities
        );
    }
} 